﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using WCBG.ToolsForUnity.Tools;
using UnityEngine.UI;
using DG.Tweening;

/// <summary>
/// 牙刷
/// </summary>
public class DragCleaner : Object3dDragBase {

    public float _max_y;
    public string _cleannerPath;
    Transform _toothdirty;
    Camera _cam;
    Transform _effect;
    bool _isOpenWaterEffect;
    BrushTeeth _brushTeeth;

    GameObject _cleaner;

    public override void InitComponet()
    {
        base.InitComponet();
        _cam = ToothacheGameManager.Instance._cam;
        _effect = transform.Find("502004097");
        _loopAudioName = HospitalConsts.yinxiao_pentoupenshui;
        InvokeRepeating("OnShake", 5f, 10f);
        _brushTeeth = ToothacheGameManager.Instance.brushTeeth;
    }

    public override void OnBeginDrag(PointerEventData eventData)
    {
        base.OnBeginDrag(eventData);

        _effect.SetActive(true);
        ActiveLoopAudio(true);
        _brushTeeth._isOnOperation = true;
    }

    public override Vector3 Get3DPosition()
    {
        Plane plane = new Plane(_cam.transform.forward * -1, new Vector3(.4f, 1f, -0.96f));
        Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
        float dis;
        if (plane.Raycast(ray, out dis))
        {
            Vector3 point = ray.GetPoint(dis);
            return point;
        }

        return Vector3.zero;
    }

    public override void OnDrag(PointerEventData eventData)
    {
        base.OnDrag(eventData);

        Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, Mathf.Infinity, 1 << LayerMask.NameToLayer("Draggable")))
        {
            _targetDragObjectPosition = hit.point;
            _targetDragObjectRotation = Quaternion.LookRotation(hit.normal * -1);
        }
        else
        {
            _targetDragObjectRotation = Quaternion.LookRotation(_cam.transform.forward);
        }

        if (Physics.Raycast(ray, out hit, Mathf.Infinity, 1 << LayerMask.NameToLayer("Wash")))
        {

            Debug.Log(hit.transform.name);
            if (hit.transform.name.StartsWith("tooth_Residual"))
            {
                _toothdirty = hit.transform;
                _toothdirty.GetComponent<ToothDirty>().OnBrushCleanUpdate();
            }
        }

    }

    public override void OnEndDrag(PointerEventData eventData)
    {
        base.OnEndDrag(eventData);

        _effect.SetActive(false);
        ActiveLoopAudio(false);
        _brushTeeth._isOnOperation = false;
    }

    protected override void OnShake()
    {
        base.OnShake();
        if (!_isOnTweening && !_onDragging && !_brushTeeth._isOnOperation && !_brushTeeth._iscleanfinished)
        {
            HospitalUtil.PlayAudio(HospitalConsts.audio_huandong);
            transform.parent.GetComponent<Animator>().CrossFade("Shake", .1f);
        }
    }
}
